﻿using System;
using System.Collections.Generic;
using System.Text;
using Common;
using System.Threading;
namespace Server
{
    class Program
    {
        static void Main(string[] args)
        {
            while (true)
            {
                IntPtr pipeHandle = NamedPipeLib.CreateNamedPipe(
                             @"\\.\pipe\MyPipe",
                             NamedPipeLib.PIPE_ACCESS_DUPLEX,
                             NamedPipeLib.PIPE_TYPE_MESSAGE | NamedPipeLib.PIPE_READMODE_MESSAGE,
                             NamedPipeLib.PIPE_UNLIMITED_INSTANCES,
                             1024,
                             1024,
                             0,
                             IntPtr.Zero);

                uint u = NamedPipeLib.GetLastError();

                if (pipeHandle.ToInt32() == NamedPipeLib.INVALID_HANDLE_VALUE)
                {
                    Console.WriteLine("创建管道出错");
                    return;
                }

                bool connected = NamedPipeLib.ConnectNamedPipe(pipeHandle, null) ? true : (NamedPipeLib.GetLastError() == NamedPipeLib.ERROR_PIPE_CONNECTED);

                if (connected)
                {
                    ThreadPool.QueueUserWorkItem(new WaitCallback(ReadMessage), pipeHandle);
                }
                else
                {
                    NamedPipeLib.CloseHandle(pipeHandle);
                }
            }
 
        }

        public static void ReadMessage(object arg)
        {
            IntPtr pipeHandle = (IntPtr)arg;
  
            byte[] numReadWritten = new byte[4];
            byte[] intBytes = new byte[4];

            NamedPipeLib.ReadFile(pipeHandle, intBytes, 4, numReadWritten, 0);

            int len = BitConverter.ToInt32(intBytes, 0);

            byte[] recBuffer=new byte[len];

            NamedPipeLib.ReadFile(pipeHandle, recBuffer, (uint)len, numReadWritten, 0);

            string str=Encoding.UTF8.GetString(recBuffer);

            Console.WriteLine(str);

            NamedPipeLib.FlushFileBuffers(pipeHandle);

            NamedPipeLib.DisconnectNamedPipe(pipeHandle);

            NamedPipeLib.CloseHandle(pipeHandle); 
        }
    }
}
